package site.tuluan.sp4j.module.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import site.tuluan.sp4j.common.core.component.cache.ICache;
import site.tuluan.sp4j.common.core.domain.entity.SysMenuEntity;
import site.tuluan.sp4j.common.core.service.permission.IPermissionService;
import site.tuluan.sp4j.common.utils.StringUtils;
import site.tuluan.sp4j.module.sys.mapper.SysMenuMapper;
import site.tuluan.sp4j.module.sys.service.ISysMenuService;

import javax.annotation.Resource;
import java.util.Set;

@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenuEntity> implements ISysMenuService, IPermissionService {
    private static final Logger log = LoggerFactory.getLogger(SysMenuServiceImpl.class);

    /**
     * 用户权限前缀
     */
    private static final String PERMISSION_PREFIX = "perm:";

    @Resource
    private ICache cache;

    @Resource
    private SysMenuMapper sysMenuMapper;

    /**
     * 获取用户所拥有的权限集
     * @param userId 用户ID
     * @return 用户所拥有的权限集
     */
    @Override
    public Set<String> getPermissionByUserId(String userId) {
        // 用户的权限存储在缓存中，如果缓存中没有的话，从数据库中取
        Set<String> permSet = cache.getCache(PERMISSION_PREFIX + userId);

        if (permSet == null || permSet.isEmpty()) {
            permSet = sysMenuMapper.selectPermissionSetByUserId(userId);
        }
        if (!permSet.isEmpty()) {
            cache.setCache(PERMISSION_PREFIX + userId, permSet);
        }

        return permSet;
    }

    /**
     * 同一目录下的菜单名是否唯一
     * @param menu 菜单信息
     * @return 是否在同名菜单
     */
    @Override
    public boolean menuNameExist(SysMenuEntity menu) {
        String menuId = StringUtils.isEmpty(menu.getId()) ? "-1" : menu.getId();
        QueryWrapper<SysMenuEntity> param = new QueryWrapper<>();
        param.lambda()
                .eq(SysMenuEntity::getName, menu.getName())
                .eq(SysMenuEntity::getParentId, menu.getParentId())
                .eq(SysMenuEntity::getStatus, SysMenuEntity.STATUS_NORMAL).ne(SysMenuEntity::getId, menuId);
        return sysMenuMapper.exists(param);
    }
}
